package com.czy.owner.ui.store;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.czy.owner.R;
import com.czy.owner.adapter.NearStoreListAdapter;
import com.czy.owner.api.BindStoreApi;
import com.czy.owner.api.NearStoreListApi;
import com.czy.owner.api.StoreSearchApi;
import com.czy.owner.callback.RecycleViewDivider;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.NearStoreListModel;
import com.czy.owner.entity.OwnerInfoModel;
import com.czy.owner.entity.StoreDataModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.MyLoadView;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easemob.cases.MessageHelper;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StoreSearchActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener {


    private static final int SEARCH_TYPE = 1;
    @BindView(R.id.et_store_search)
    EditText etStoreSearch;
    @BindView(R.id.img_clear)
    ImageView imgClear;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private NearStoreListAdapter adapter;
    private int page = 1;
    private Handler handler = new Handler();
    private String session = "";
    private double gprsX; //经度
    private double gprsY;//纬度
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private MyLoadView myLoadView;
    //标识，用于判断是否只显示一次定位信息和用户重新定位
    private boolean isFirstLoc = true;
    private String etContent;
    private OwnerInfoModel ownerInfoModel;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_store_search;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        initLoc();
        myLoadView = new MyLoadView(this, "正在加载");
        session = UserHelper.getInstance().getSession(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(StoreSearchActivity.this));
        recyclerView.setAdapterWithProgress(adapter = new NearStoreListAdapter(StoreSearchActivity.this));
        recyclerView.addItemDecoration(new RecycleViewDivider(StoreSearchActivity.this, LinearLayoutManager.VERTICAL, R.drawable.shape_recyclerview_divider_decoration));
        recyclerView.setEmptyView(R.layout.view_empty_common);
        recyclerView.setErrorView(R.layout.view_error_net);
        adapter.setMore(R.layout.view_more, StoreSearchActivity.this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<NearStoreListModel>() {
            @Override
            public void onItemClick(View view,int position, NearStoreListModel o) {
                Intent ti = new Intent(StoreSearchActivity.this, NoBindStoreDetailActivity.class);
                ti.putExtra("storeName", o.getStoreName());
                ti.putExtra("stroeLogo", o.getStroeLogo());
                ti.putExtra("description", o.getDescription());
                ti.putExtra("serviceNumber", o.getServiceNumber());
                ti.putExtra("storeLocation", o.getStoreLocation());
                ti.putExtra("gprsX", o.getGprsX());
                ti.putExtra("gprsY", o.getGprsY());
                ti.putExtra("storeId", o.getStoreId());
                ti.putExtra("banners", (Serializable) o.getResList());
                startActivityForResult(ti, SEARCH_TYPE);

            }
        });
        adapter.setBindStoreListener(new NearStoreListAdapter.BindStoreListener() {
            @Override
            public void onBindClickListener(int storeId) {
                SharedPreferencesUtils.setParam(StoreSearchActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND_DIALOG, storeId);
                SharedPreferencesUtils.setParam(StoreSearchActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND, true);
                if(checkLoginState()){
                    BindDialog(StoreSearchActivity.this.getString(R.string.bind_store_title), StoreSearchActivity.this.getString(R.string.sure_bind), StoreSearchActivity.this.getString(R.string.cancle_bind), storeId);
                }

            }
        });
        etStoreSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                /*隐藏软键盘*/
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    if (inputMethodManager.isActive()) {
                        inputMethodManager.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    etContent = etStoreSearch.getText().toString().trim();
                    if (etContent == null || TextUtils.isEmpty(etContent)) {
                        PhoneUtils.ShowToastMessage(StoreSearchActivity.this, "输入的内容不能为空");
                    } else {
                        page=1;
                        getDataList(etContent);
                    }


                    return true;
                }
                return false;


            }
        });

        etStoreSearch.addTextChangedListener(new EditChangedListener());
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                if (!PhoneUtils.isNetworkConnected(StoreSearchActivity.this)) {
                    adapter.pauseMore();
                    recyclerView.showError();
                    return;
                }
                page++;
                getDataList(etContent);

            }
        }, 1000);
    }


    public void getDataList(String ettext) {
        if (page == 1) {
            myLoadView.ShowLoadView();
            adapter.clear();
        }

        StoreSearchApi storeSearchListApi = new StoreSearchApi(new HttpOnNextListener<List<NearStoreListModel>>() {
            @Override
            public void onNext(List<NearStoreListModel> list) {
                myLoadView.CancleLoadView();
                setNearStoreList(list);

            }


            @Override
            public void onCacheNext(String cache) {

                super.onCacheNext(cache);
                myLoadView.CancleLoadView();
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<NearStoreListModel>>>() {
                }.getType();
                BaseResultEntity<List<NearStoreListModel>> cacheList = gson.fromJson(cache, type);
                setNearStoreList(cacheList.getData());
            }

            @Override
            public void onError(Throwable e) {
                myLoadView.CancleLoadView();
                super.onError(e);
                PhoneUtils.ShowToastMessage(StoreSearchActivity.this, e.getMessage());
            }

        }, this);
        storeSearchListApi.setGprsX(String.valueOf(gprsX));
        storeSearchListApi.setGprsY(String.valueOf(gprsY));
        storeSearchListApi.setLikeName(ettext);
        storeSearchListApi.setPage(page + "");
        storeSearchListApi.setSize("10");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(storeSearchListApi);


    }

    private void setNearStoreList(List<NearStoreListModel> list) {
        if (list.size() < 10) {
            adapter.stopMore();
        }
        adapter.addAll(list);
    }

    //  定位回调监听事件
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    gprsX = amapLocation.getLongitude();//获取经度
                    gprsY = amapLocation.getLatitude();//获取纬度
                    amapLocation.getAccuracy();//获取精度信息
                    if (isFirstLoc) {

                        isFirstLoc = false;
                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("qwe", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //定位初始化控件配置

    private void initLoc() {
        locationClient = new AMapLocationClient(StoreSearchActivity.this);
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }


    class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etStoreSearch.getText().toString().trim().length() > 0) {
                imgClear.setVisibility(View.VISIBLE);
            } else {
                imgClear.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (etStoreSearch.getText().toString().trim().length() > 0) {
                imgClear.setVisibility(View.VISIBLE);
            } else {
                imgClear.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != locationClient) {
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @OnClick({R.id.img_clear, R.id.tv_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_clear:
                etStoreSearch.setText("");
                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

    private void BindDialog(String title, String sure, String cancle, final int storeId) {
        new UniversalDialog(StoreSearchActivity.this).builder().setTitle(title)
                .setPositiveButton(sure, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BindStoreRequest(storeId);
                    }
                }).setNegativeButton(cancle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();
    }

    private void BindStoreRequest(final int storeId) {
        ownerInfoModel = UserHelper.getInstance().getOwnerInfoModel(StoreSearchActivity.this);
        BindStoreApi bindStoreApi = new BindStoreApi(new HttpOnNextListener<StoreDataModel>() {
            @Override
            public void onNext(StoreDataModel model) {
                Gson gson = new GsonBuilder().create();
                String data = gson.toJson(model);
                MyLog.e("asus", "data" + data);
                UserHelper.getInstance().saveChainStores(StoreSearchActivity.this, data);
                MessageHelper.getInstance().reset();
                EMClient.getInstance().login(UserHelper.getInstance().getUserInfoModel(StoreSearchActivity.this).getImKey(), UserHelper.getInstance().getUserInfoModel(StoreSearchActivity.this).getImPasswd(), new EMCallBack() {//回调
                    @Override
                    public void onSuccess() {
                        MessageHelper.getInstance().getUserProfileManager().setCurrentUser(UserHelper.getInstance().getUserInfoModel(StoreSearchActivity.this.getApplicationContext()).getNickName(),
                                UserHelper.getInstance().getUserInfoModel(StoreSearchActivity.this.getApplicationContext()).getUserLogo());
                        EMClient.getInstance().groupManager().loadAllGroups();
                        EMClient.getInstance().chatManager().loadAllConversations();
                        MyLog.d("King", "登录聊天服务器成功！");
                    }

                    @Override
                    public void onProgress(int progress, String status) {

                    }

                    @Override
                    public void onError(int code, String message) {
                        MyLog.d("King", "登录聊天服务器失败！" + code + "|" + message);
                    }
                });
                for (int i = 0; i <model.getChainStores().size(); i++) {
                    if(model.getChainStores().get(i).getStoreId()==storeId){
                        String storeName = model.getChainStores().get(i).getStoreName();
                        ownerInfoModel.setStoreName(storeName);
                        break;
                    }
                }
                ownerInfoModel.setStoreId(storeId);
                ownerInfoModel.setBindStoreId(storeId);
                UserHelper.getInstance().setOwnerInfoModel(StoreSearchActivity.this, ownerInfoModel);
                UserHelper.getInstance().setSelectStoreId(StoreSearchActivity.this, storeId);
                SharedPreferencesUtils.setParam(StoreSearchActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, storeId);
                PhoneUtils.ShowToastMessage(StoreSearchActivity.this, "绑定成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                PhoneUtils.ShowToastMessage(StoreSearchActivity.this, e.getMessage());
            }
        }, StoreSearchActivity.this);

        bindStoreApi.setSession(UserHelper.getInstance().getSessionInfoModel(StoreSearchActivity.this).getSession());
        bindStoreApi.setStoreId(storeId + "");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(bindStoreApi);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==SEARCH_TYPE&&resultCode==RESULT_OK){
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferencesUtils.remove(Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND);
    }
}
